<template>
  <div
    class="ml-switch"
    :class="{ 'is-checked': value }"
    @click="handleClick"
  >
 
    <span class="ml-switch_core" ref="core">
      <span class="ml-switch_button"> </span>
    </span>
     <input type="checkbox" class="ml-switch_input" :name="name"/>
  </div>
</template>

<script>
export default {
  name: "MlSwitch",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    activeColor: {
      type: String,
      default: "",
    },
    inactiveColor: {
      type: String,
      default: "",
    },
    name:{
        type:String,
        default:""
    }
  },
  mounted() {
    this.setColor();
  },
  methods: {
    async handleClick() {
      this.$emit("input", !this.value);
      await this.$nextTick();
      this.setColor();
    },
    setColor() {
      if (this.activeColor || this.inactiveColor) {
        let color = this.value ? this.activeColor : this.inactiveColor;
        this.$refs.core.style.borderColor = color;
        this.$refs.core.style.backgroundColor = color;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.ml-switch {
  display: inline-flex;
  align-items: center;
  font-size: 14px;
  line-height: 20px;
  height: 20px;
  vertical-align: middle;
  .ml-switch_input{
      position: absolute;
      width: 0;
      height: 0;
      opacity: 0;
      margin: 0;
  }
  .ml-switch_core {
    margin: 0;
    display: inline-block;
    position: relative;
    width: 40px;
    height: 20px;
    border: 1px solid #dcdfe6;
    outline: none;
    border-radius: 10px;
    box-sizing: border-box;
    background: #dcdfe6;
    cursor: pointer;
    transition: border-color 0.3s, background-color 0.3s;
    vertical-align: middle;
    .ml-switch_button {
      position: absolute;
      top: 1px;
      left: 1px;
      border-radius: 100%;
      transition: all 0.3s;
      width: 16px;
      height: 16px;
      background-color: #fff;
    }
  }
}
.ml-switch.is-checked {
  .ml-switch_core {
    border-color: #409eff;
    background-color: #409eff;
    .ml-switch_button {
      transform: translateX(20px);
    }
  }
}
</style>